<template>
  <div class="app-container">
    <div v-if="!open && !isView"
         class="body">
      <el-form :model="queryParams"
               ref="queryForm"
               size="small"
               :inline="true"
               v-show="showSearch"
               label-width="68px">
        <el-form-item label="客户姓名"
                      prop="nickName">
          <el-input v-model="queryParams.nickName"
                    placeholder="请输入客户姓名"
                    clearable
                    style="width: 240px"
                    @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="手机号码"
                      prop="phonenumber">
          <el-input v-model="queryParams.phonenumber"
                    placeholder="请输入手机号码"
                    clearable
                    style="width: 240px"
                    @keyup.enter.native="handleQuery" />
        </el-form-item>

        <el-form-item label="审核状态"
                      prop="auditStatus">
          <el-select v-model="queryParams.auditStatus"
                     placeholder="审核状态"
                     clearable
                     style="width: 240px">
            <el-option v-for="dict in dict.type.sys_audit_status"
                       :key="dict.value"
                       :label="dict.label"
                       :value="dict.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态"
                      prop="status">
          <el-select v-model="queryParams.status"
                     placeholder="客户状态"
                     clearable
                     style="width: 240px">
            <el-option v-for="dict in dict.type.sys_normal_disable"
                       :key="dict.value"
                       :label="dict.label"
                       :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker v-model="dateRange"
                          style="width: 240px"
                          value-format="yyyy-MM-dd"
                          type="daterange"
                          range-separator="-"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     icon="el-icon-search"
                     size="mini"
                     @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh"
                     size="mini"
                     @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10"
              class="mb8">
        <el-col :span="1.5">
          <el-button type="primary"
                     plain
                     icon="el-icon-plus"
                     size="mini"
                     @click="handleAdd"
                     v-hasPermi="['system:user:add']">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success"
                     plain
                     icon="el-icon-edit"
                     size="mini"
                     :disabled="single"
                     @click="handleUpdate"
                     v-hasPermi="['system:custom:edit']">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger"
                     plain
                     icon="el-icon-delete"
                     size="mini"
                     :disabled="multiple"
                     @click="handleDelete"
                     v-hasPermi="['system:custom:remove']">删除</el-button>
        </el-col>

        <right-toolbar :showSearch.sync="showSearch"
                       @queryTable="getList"
                       :columns="columns"></right-toolbar>
      </el-row>

      <el-table v-loading="loading"
                :data="customList"
                height="calc(100vh - 330px)"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection"
                         width="55"
                         align="center" />
        <el-table-column label="客户编号"
                         align="center"
                         key="userId"
                         prop="userId"
                         v-if="columns[0].visible" />
        <el-table-column label="客户姓名"
                         align="center"
                         key="nickName"
                         prop="nickName"
                         v-if="columns[1].visible"
                         :show-overflow-tooltip="true" />
        <el-table-column label="注册角色"
                         align="center"
                         prop="roleType"
                         v-if="columns[2].visible"
                         :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_role_type"
                      :value="scope.row.roleType" />
          </template>
        </el-table-column>
        <el-table-column label="工作单位"
                         align="center"
                         key="deptName"
                         prop="deptName"
                         v-if="columns[3].visible"
                         :show-overflow-tooltip="true" />
        <el-table-column label="手机号码"
                         align="center"
                         key="phonenumber"
                         prop="phonenumber"
                         v-if="columns[4].visible"
                         :show-overflow-tooltip="true" />
        <el-table-column label="邮箱"
                         align="center"
                         key="email"
                         show-overflow-tooltip
                         prop="email"
                         v-if="columns[5].visible"
                         width="120" />
        <el-table-column label="注册时间"
                         align="center"
                         key="createTime"
                         prop="createTime"
                         v-if="columns[6].visible"
                         width="160" />
        <el-table-column label="注册类型"
                         align="center"
                         key="registerType"
                         prop="registerType"
                         v-if="columns[7].visible"
                         :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_register_type"
                      :value="scope.row.registerType" />
          </template>
        </el-table-column>

        <el-table-column label="审核状态"
                         align="center"
                         key="auditStatus"
                         prop="auditStatus"
                         v-if="columns[8].visible"
                         :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_audit_status"
                      :value="scope.row.auditStatus" />
          </template>
        </el-table-column>

        <el-table-column label="状态"
                         align="center"
                         key="status"
                         v-if="columns[9].visible">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status"
                       active-value="0"
                       inactive-value="1"
                       @change="handleStatusChange(scope.row)"
                       :disabled="scope.row.status==1">

            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作"
                         align="center"
                         width="200"
                         class-name="small-padding fixed-width">
          <template slot-scope="scope"
                    v-if="scope.row.userId !== 1">
            <!-- 待审核时，显示编辑与审核；已审核时，显示编辑和设置上级；审核不通过，显示编辑和删除          -->

            <el-button size="mini"
                       type="text"
                       icon="el-icon-edit"
                       @click="handleView(scope.row)"
                       v-if="scope.row.auditStatus !='0'"
                       v-hasPermi="['system:custom:edit']">详情</el-button>
            <el-button size="mini"
                       type="text"
                       icon="el-icon-edit"
                       @click="handleUpdate(scope.row)"
                       v-if="scope.row.auditStatus ==='1'"
                       v-hasPermi="['system:custom:edit']">修改</el-button>
            <el-button size="mini"
                       type="text"
                       icon="el-icon-delete"
                       @click="handleDelete(scope.row)"
                       v-if="scope.row.auditStatus ==='2'"
                       v-hasPermi="['system:custom:remove']">删除</el-button>

            <el-button size="mini"
                       type="text"
                       icon="el-icon-edit"
                       @click="handleAudit(scope.row)"
                       v-if="scope.row.auditStatus ==='0'"
                       v-hasPermi="['system:custom:audit']">审核</el-button>

            <el-button size="mini"
                       type="text"
                       icon="el-icon-edit"
                       @click="setSuperior(scope.row)"
                       v-if="scope.row.auditStatus ==='1'"
                       v-hasPermi="['system:custom:setSuperior']">设置上级</el-button>

          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0"
                  :total="total"
                  :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize"
                  @pagination="getList" />
    </div>

    <!-- 客户详情配置对话框 -->
    <div v-if="isView"
         class="editdata">
      <p class="back"><span class="el-icon-arrow-left"
              @click="goBack">返回</span> / <span>详情</span></p>

      <el-form ref="form"
               :model="viewForm"
               label-width="100px">
        <div class="editbox">
          <h3>{{title}}</h3>
          <el-row>
            <el-col :span="8">
              <el-form-item label="注册角色">
                <el-select readOnly
                           disabled
                           style="width: 240px"
                           v-model="viewForm.roleType">
                  <el-option v-for="dict in dict.type.sys_role_type"
                             :key="dict.value"
                             :label="dict.label"
                             :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户姓名">
                <el-input v-model="viewForm.nickName"
                          maxlength="30"
                          style="width: 240px"
                          readOnly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="工作单位">
                <el-input v-model="viewForm.deptName"
                          style="width: 240px"
                          maxlength="30"
                          readOnly />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="手机号码">
                <el-input v-model="viewForm.phonenumber"
                          style="width: 240px"
                          maxlength="11"
                          readOnly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="邮箱">
                <el-input v-model="viewForm.email"
                          style="width: 240px"
                          maxlength="30"
                          readOnly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="注册时间">
                <el-input v-model="viewForm.createTime"
                          style="width: 240px"
                          maxlength="30"
                          readOnly />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="审核状态">
                <el-select readOnly
                           disabled
                           v-model="viewForm.auditStatus"
                           style="width: 240px">
                  <el-option v-for="dict in dict.type.sys_audit_status"
                             :key="dict.value"
                             :label="dict.label"
                             :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="状态">
                <template>
                  <el-switch v-model="viewForm.status"
                             disabled
                             active-value="0"
                             inactive-value="1"
                             @change="handleStatusChange(form)"></el-switch>
                </template>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="最后登录时间">
                <el-input v-model="viewForm.createTime"
                          maxlength="30"
                          style="width: 240px"
                          readOnly />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="设置上级">
                <el-select readOnly
                           multiple
                           disabled
                           v-model="viewForm.superiorIds"
                           style="width: 240px">
                  <el-option v-for="dict in superiorOptions"
                             :key="dict.userId"
                             :label="dict.nickName"
                             :value="dict.userId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="归属部门"
                            prop="deptId">
                <treeselect v-model="viewForm.deptId"
                            style="width: 240px"
                            disabled
                            :options="deptOptions"
                            :show-count="true"
                            placeholder="请选择归属部门" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="角色">
                <el-select v-model="viewForm.roleIds"
                           multiple
                           disabled
                           placeholder="请选择角色">
                  <el-option v-for="item in roleOptions"
                             :key="item.roleId"
                             :label="item.roleName"
                             :value="item.roleId"
                             :disabled="item.status == 1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="editbox editfooter">

          <h3>审核</h3>
          <div>
            <div class="footbox">
              <img src="../../../assets/images/custom/sh@2x.png"
                   alt="">
              <span>审核通过</span>
              <img src="../../../assets/images/custom/checkbox@2x.png"
                   class="icon_box"
                   v-if="viewForm.auditStatus==1"
                   alt="">
            </div>

            <div class="footbox">
              <img src="../../../assets/images/custom/sh@2x.png"
                   alt="">
              <span>审核不通过</span>
              <img src="../../../assets/images/custom/checkbox@2x.png"
                   class="icon_box"
                   v-if="viewForm.auditStatus==2"
                   alt="">
            </div>
          </div>
        </div>

      </el-form>
    </div>

    <!-- 添加或修改客户配置对话框 -->
    <div v-if="open && !isView"
         class="editdata">
      <p class="back"><span class="el-icon-arrow-left"
              @click="goBack">返回</span> / <span>编辑</span></p>

      <el-form ref="form"
               :model="form"
               :rules="rules"
               label-width="100px">
        <div class="editbox">
          <h3>{{title}}</h3>
          <el-row>
            <el-col :span="8">
              <el-form-item label="注册角色"
                            prop="roleType">
                <el-select style="width: 240px"
                           v-model="form.roleType"
                           placeholder="请选择注册角色">
                  <el-option v-for="dict in dict.type.sys_role_type"
                             :key="dict.value"
                             :label="dict.label"
                             :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户姓名"
                            prop="nickName">
                <el-input v-model="form.nickName"
                          placeholder="请输入客户姓名"
                          style="width: 240px"
                          maxlength="30" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="工作单位"
                            prop="deptName">
                <el-input v-model="form.deptName"
                          placeholder="请输入工作单位"
                          style="width: 240px"
                          maxlength="30" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8"
                    v-if="form.registerType==1">
              <el-form-item label="手机号码"
                            prop="phonenumber">
                <el-input v-model="form.phonenumber"
                          placeholder="请输入手机号码"
                          style="width: 240px"
                          maxlength="11" />
              </el-form-item>
            </el-col>
            <el-col :span="8"
                    v-if="form.registerType==2">
              <el-form-item label="手机号码">
                <el-input v-model="form.phonenumber"
                          placeholder="请输入手机号码"
                          style="width: 240px"
                          maxlength="11" />
              </el-form-item>
            </el-col>
            <el-col :span="8"
                    v-if="form.registerType==2">
              <el-form-item label="邮箱"
                            prop="email">
                <el-input v-model="form.email"
                          placeholder="请输入邮箱"
                          style="width: 240px"
                          maxlength="30" />
              </el-form-item>
            </el-col>
            <el-col :span="8"
                    v-if="form.registerType==1">
              <el-form-item label="邮箱">
                <el-input v-model="form.email"
                          placeholder="请输入邮箱"
                          style="width: 240px"
                          maxlength="30" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="注册时间"
                            prop="createTime">
                <el-input v-model="form.createTime"
                          maxlength="30"
                          style="width: 240px"
                          readOnly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="审核状态">
                <el-select v-model="form.auditStatus"
                           style="width: 240px">
                  <el-option v-for="dict in dict.type.sys_audit_status"
                             :key="dict.value"
                             :label="dict.label"
                             :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="状态">
                <template>
                  <el-switch v-model="form.status"
                             active-value="0"
                             inactive-value="1"
                             @change="handleStatusChange(form)"></el-switch>
                </template>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="最后登录时间">
                <el-input v-model="form.createTime"
                          maxlength="30"
                          style="width: 240px"
                          readOnly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="设置上级">
                <el-select v-model="form.superiorIds"
                           multiple
                           filterable
                           style="width: 240px">
                  <el-option v-for="dict in superiorOptions"
                             :key="dict.userId"
                             :label="dict.nickName"
                             :value="dict.userId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="归属部门"
                            prop="deptId">
                <treeselect v-model="form.deptId"
                            style="width: 240px"
                            :options="deptOptions"
                            :show-count="true"
                            placeholder="请选择归属部门" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="角色"
                            prop="roleIds">
                <el-select v-model="form.roleIds"
                           multiple
                           style="width: 240px"
                           placeholder="请选择角色">
                  <el-option v-for="item in roleOptions"
                             :key="item.roleId"
                             :label="item.roleName"
                             :value="item.roleId"
                             :disabled="item.status == 1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="editbox editfooter">

          <span @click="cancel"
                class="cancel btn">取消</span>
          <span type="primary"
                @click="submitForm"
                class="save btn">保存</span>
        </div>

      </el-form>
    </div>

    <!--列表审核-->
    <el-dialog :title="auditForm.title"
               :visible.sync="auditForm.open"
               width="80%"
               append-to-body>
      <el-form ref="auditForm"
               :model="auditForm"
               :rules="listAuditRules"
               label-width="80px">

        <el-row>
          <el-col :span="12">
            <el-form-item>
              <el-radio-group v-model="auditForm.auditStatus">
                <el-radio v-for="dict in dict.type.sys_audit_status"
                          v-if="dict.value!= '0'"
                          :key="dict.value"
                          :label="dict.value">{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="auditForm.auditStatus == 1">
          <el-col :span="8">
            <el-form-item label="归属部门"
                          prop="deptId">
              <treeselect v-model="auditForm.deptId"
                          style="width: 240px"
                          :options="deptOptions"
                          :show-count="true"
                          placeholder="请选择归属部门" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="角色"
                          prop="roleIds">
              <el-select v-model="auditForm.roleIds"
                         multiple
                         style="width: 240px"
                         placeholder="请选择角色">
                <el-option v-for="item in roleOptions"
                           :key="item.roleId"
                           :label="item.roleName"
                           :value="item.roleId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>

      </el-form>

      <div slot="footer"
           class="dialog-footer">
        <el-button type="primary"
                   @click="auditSubmitForm">确 定</el-button>
        <el-button @click="auditCancel">取 消</el-button>
      </div>

    </el-dialog>

    <!-- 客户导入对话框 -->
    <el-dialog :title="upload.title"
               :visible.sync="upload.open"
               width="400px"
               append-to-body>
      <el-upload ref="upload"
                 :limit="1"
                 accept=".xlsx, .xls"
                 :headers="upload.headers"
                 :action="upload.url + '?updateSupport=' + upload.updateSupport"
                 :disabled="upload.isUploading"
                 :on-progress="handleFileUploadProgress"
                 :on-success="handleFileSuccess"
                 :auto-upload="false"
                 drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center"
             slot="tip">
          <div class="el-upload__tip"
               slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的客户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary"
                   :underline="false"
                   style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer"
           class="dialog-footer">
        <el-button type="primary"
                   @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 设置上级对话框 -->
    <el-dialog :title="superior.title"
               :visible.sync="superior.open"
               width="80%"
               append-to-body>
      <el-form ref="form"
               :model="superiorForm"
               label-width="80px">

        <el-row>
          <el-col :span="12">
            <el-form-item>
              <el-col :span="8">
                <el-form-item label="设置上级">
                  <el-select v-model="superiorForm.superiorIds"
                             placeholder="请选择上级姓名并选择"
                             style="width: 360px"
                             multiple
                             filterable>
                    <el-option v-for="dict in superiorOptions"
                               :key="dict.userId"
                               :label="dict.nickName"
                               :value="dict.userId"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer"
           class="dialog-footer">
        <el-button type="primary"
                   @click="superiorSubmitForm">确 定</el-button>
        <el-button @click="superiorCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCustom, getCustom, delCustom, addCustom, updateCustom, changeCustomStatus, auditCustom, isRegisterUserlist, setSuperior } from "@/api/system/custom";
import { deptTreeSelect } from "@/api/system/user";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "User",
  dicts: ['sys_normal_disable', 'sys_user_sex', 'sys_role_type', 'sys_audit_status', 'sys_register_type'],
  components: { Treeselect },
  data () {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户表格数据
      customList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: [],

      // 是否显示弹出层
      open: false,
      isView: false,//是否查看页面
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],

      //客户注册角色
      roleTypeOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},

      viewForm: {

      },


      defaultProps: {
        children: "children",
        label: "label"
      },

      // 客户审核参数
      auditForm: {
        // 是否显示弹出层（客户导入）
        open: false,
        // 弹出层标题（客户导入）
        title: "",
        auditStatus: "1", //默认显示通过
        userId: "",
        isRegister: "",
        deptId: "",
        roleIds: []
      },


      // 设置上级参数
      superior: {
        // 是否显示弹出层（客户导入）
        open: false,
        // 弹出层标题（客户导入）
        title: "",
      },
      superiorForm: {
        userId: "",
        superiorIds: "",
      },

      superiorOptions: [],


      // 客户导入参数
      upload: {
        // 是否显示弹出层（客户导入）
        open: false,
        // 弹出层标题（客户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的客户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
        auditStatus: undefined,
        //默认已注册客户
        isRegister: 1
      },
      // 列信息
      columns: [
        { key: 0, label: `客户编号`, visible: true },
        { key: 1, label: `客户姓名`, visible: true },
        { key: 2, label: `角色`, visible: true },
        { key: 3, label: `工作单位`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `邮箱`, visible: true },
        { key: 6, label: `注册时间`, visible: true },
        { key: 7, label: `注册类型`, visible: true },
        { key: 8, label: `审核状态`, visible: true },
        { key: 9, label: `状态`, visible: true }
      ],
      // 表单校验
      rules: {
        roleType: { required: true, message: "注册角色不能为空", trigger: "blur" },
        nickName: [
          { required: true, message: "客户姓名不能为空", trigger: "blur" }
        ],
        deptName: [
          { required: true, message: "工作单位不能为空", trigger: "blur" }
        ],

        email: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            required: true,
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phonenumber: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        deptId: [
          { required: true, message: "请选择部门", trigger: "blur" }
        ],
        roleIds: [
          { required: true, message: "请选择角色", trigger: "blur" }
        ],
      },

       listAuditRules: {
        deptId: [
          { required: true, message: "请选择部门", trigger: "blur" }
        ],
        roleIds: [
          { required: true, message: "请选择角色", trigger: "blur" }
        ],
      },
    };
  },
  watch: {
  },

  mounted () {
    if (this.$route.query) {
      var operationType = this.$route.query.operationType
      var userId = this.$route.query.userId;
      var redirect = this.$route.query.redirect
      if (redirect && redirect != undefined) {
        this.redirect = redirect;
      }

      if (operationType == "edit") {
        this.reset();
        getCustom(userId).then(response => {
          this.form = response.data;
          this.roleOptions = response.roles;
          this.$set(this.form, "roleIds", response.roleIds);
          this.open = true;
          this.title = "修改客户";
        });
      } else if (operationType == "audit") {
        this.auditForm.open = true;
        this.auditForm.userId = userId;
      }
    }

  },


  created () {
    this.getList();
    this.getDeptTree();
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });
  },
  methods: {

    /** 查询部门下拉树结构 */
    getDeptTree () {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },

    /**设置上级按钮操作*/
    setSuperior (row) {
      var userId = row.userId;
      this.superiorForm.userId = userId;
      this.superiorForm.superior = undefined;
      this.getSuperior();
      this.superior.title = "设置上级";
      this.superior.open = true;

      getCustom(userId).then(response => {
        this.$set(this.superiorForm, "superiorIds", response.data.superiorIds);
      });
    },


    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      const userId = row.userId || this.ids;
      this.superiorForm.userId = userId;
      this.getSuperior();
      getCustom(userId).then(response => {
        this.form = response.data;
        this.$set(this.form, "superiorIds", response.data.superiorIds);
        this.roleOptions = response.roles;
        this.$set(this.form, "roleIds", response.roleIds);
        this.open = true;
        this.title = "修改客户";
        this.userId = response.data.userId;
        this.auditForm.auditStatus = response.data.auditStatus;
      });

    },

    /** 查看按钮 */
    handleView (row) {
      this.reset();
      this.getSuperior();
      const userId = row.userId || this.ids
      this.viewForm.userId = userId;
      getCustom(userId).then(response => {
        this.viewForm = response.data;
        this.$set(this.viewForm, "superiorIds", response.data.superiorIds);
        this.isView = true;
        this.title = "详情";
        this.roleOptions = response.roles;
        this.$set(this.viewForm, "roleIds", response.roleIds);
      });
    },

    //设置上级确定按钮
    superiorSubmitForm () {
      var superiorIds = this.superiorForm.superiorIds
      setSuperior(this.superiorForm).then(response => {
        this.$modal.msgSuccess(response.msg);
        this.auditForm.open = false;
        if (this.redirect) {
          this.$router.push(this.redirect)
        }
        this.superior.open = false;
        this.getList();
      });
    },
    //设置上级取消按钮
    superiorCancel () {
      this.superior.open = false;
      this.superiorForm.userId = undefined   },

    //获取所有已审核已注册的客户id（除了当前点击的客户）
    getSuperior () {
      var form = {};
      form.auditStatus = 1;
      form.userId = this.superiorForm.userId;
      isRegisterUserlist(form).then(response => {
        if (response.code == '200' && response.data) {
          this.superiorOptions = response.data;
        }
      });
    },


    goBack () {
      this.open = false
      this.isView = false
    },
    /** 查询客户列表 */
    getList () {
      this.loading = true;
      listCustom(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.customList = response.rows;
        this.total = response.total;
        this.loading = false;
      }
      );
    },

    // 客户状态修改
    handleStatusChange (row) {
      var isRegister = row.isRegister;
      var userName = row.userName;
      if (isRegister && isRegister == '1') {
        var registerType = row.registerType;
        if (registerType == "1") { //手机注册
          userName = row.phonenumber;
        } else if (registerType == "2") {
          userName = row.email;
        }
      }

      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + userName + '"客户吗？').then(function () {
        return changeCustomStatus(row.userId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
      if (this.redirect) {
        this.$router.push(this.redirect)
      }
    },
    auditCancel () {
      this.auditForm.open = false;
      this.reset();
      if (this.redirect) {
        this.$router.push(this.redirect)
      }
    },
    // 表单重置
    reset () {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      getCustom().then(response => {
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.$set(this.form, "roleIds", response.roleIds);
        this.open = true;
        this.title = "添加客户";
      });
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != undefined) {
            updateCustom(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              if (this.redirect) {
                this.$router.push(this.redirect)
              }
              this.getList();
            });
          } else {
            addCustom(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              if (this.redirect) {
                this.$router.push(this.redirect)
              }
              this.getList();
            });
          }
        }
      });
    },

    /**审核按钮操作*/
    handleAudit (row) {
      this.getDeptTree();
      this.auditForm.title = "审核";
      this.auditForm.deptId = null;
      this.auditForm.open = true;
      var userId = row.userId;
      this.auditForm.userId = userId;
      getCustom(userId).then(response => {
        this.roleOptions = response.roles;
        this.$set(this.auditForm, "roleIds", response.roleIds);
        this.userId = response.data.userId;
        this.auditForm.auditStatus = '1';
        this.auditForm.isRegister = response.data.isRegister
        this.auditForm.registerType = response.data.registerType
      });
    },
    /**审核提交按钮*/
    auditSubmitForm: function () {
      var that = this;
      this.$refs["auditForm"].validate(valid => {
        if (valid) {
          auditCustom(that.auditForm).then(response => {
            //需要判断当前传入的userId是否有deptId，没有的话提示
            this.$modal.msgSuccess("审核成功");
            that.getList();
            this.auditForm.open = false;
            if (this.redirect) {
              this.$router.push(this.redirect)
            }
            getCustom(that.userId).then(response => {
              this.form = response.data;
              this.userId = response.data.userId;
              this.auditForm.auditStatus = response.data.auditStatus;
            });
          });
        }
      })
    },


    //修改审核状态
    changeAuditStatus (e) {
      this.auditForm.auditStatus = e;
    },

    /** 删除按钮操作 */
    handleDelete (row) {
      const userIds = row.userId || this.ids;
      this.$modal.confirm('是否确认删除客户编号为"' + userIds + '"的数据项？').then(function () {
        return delCustom(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },


    /** 导出按钮操作 */
    handleExport () {
      this.download('system/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport () {
      this.upload.title = "客户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate () {
      this.download('system/user/importTemplate', {
      }, `user_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress (event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess (response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm () {
      this.$refs.upload.submit();
    }
  }
};
</script>
<style lang="scss" scoped>
.app-container {
  padding: 0;
  background: #fff;
  overflow: auto;
  .body {
    padding: 20px;
  }
  .editdata {
    width: 100%;
    height: 89vh;
    background: #fdfeff;
    border-radius: 0px 0px 0px 0px;
    padding: 1px 20px;
    box-sizing: border-box;
    // 面包屑样式
    .back {
      .el-icon-arrow-left {
        color: #979797;
        cursor: pointer;
      }
      span {
        font-size: 14px;
        font-family: Source Code Pro-Regular, Source Code Pro;
        font-weight: 400;
        color: #1f2329;
        line-height: 22px;
      }
    }
    // form表单样式
    .editbox {
      padding: 20px;
      box-sizing: border-box;
      background: #ffffff;
      box-shadow: 0px 4px 12px 0px rgba(211, 211, 211, 0.25);
      border-radius: 6px 6px 6px 6px;
    }
    .editfooter {
      margin-top: 20px;
      > div {
        display: flex;
        padding-bottom: 44px;
        .footbox {
          width: 150px;
          height: 96px;
          background: #f7f8fa;
          border-radius: 4px 4px 4px 4px;
          display: flex;
          justify-content: center;
          align-items: center;
          margin-right: 20px;
          position: relative;
          cursor: pointer;
          img {
            width: 23px;
            height: 24px;
          }
          .icon_box {
            width: 16px;
            height: 16px;
            position: absolute;
            right: 10px;
            top: 10px;
          }
        }
      }
    }

    h3 {
      font-family: Source Code Pro-Bold, Source Code Pro;
      font-weight: bold;
      color: #1f2329;
      line-height: 24px;
      margin: 0 0 20px 0;
      padding: 0;
    }
  }

  // 取消保存审核公用样式----后有需要 可差离出去
  .btn {
    display: inline-block;
    width: 80px;
    height: 40px;
    text-align: center;
    line-height: 40px;
    margin-right: 20px;
    cursor: pointer;
  }
  .cancel {
    background: #e6ebf0;
    border-radius: 2px 2px 2px 2px;
  }
  .save {
    background: #0b9eae;
    color: #ffffff;
    border-radius: 2px 2px 2px 2px;
  }
  .examine {
    width: 161px;
    background: #aa2290;
    color: #ffffff;
    border-radius: 4px 4px 4px 4px;
  }
}
</style>
